<?php
require_once dirname(__FILE__) . '/../includes/common.inc.php';
require_once dirname(__FILE__) . '/../includes/pdoorm.inc.php';

header('Content-Type: text/plain');


$action = MiscUtils::getParam('action', NULL);

  $sample = json_decode(MiscUtils::getParam('sp', NULL));
  $purchases = json_decode(MiscUtils::getParam('pi', NULL));
  
  /*print_r($sample);
  print_r($purchases);
  die;*/


try {
  switch ($action) {
    case 'login':
      login();
      break;
      
    case 'v1customer':
      customeradd($action);
      break;
       
    case 'updatev1customer':
        {
            $action = 'v1customer';
            customerupdate($action);
        }
      break;
   
    case 'packagepurchase':
        packagepurchaseupdate($action);
        break;
      
    default:
      break;
  }
} catch (PDOException $e) {
  echo $e->getMessage();
}

function _months($from, $to) {
  $result = array();
  for ($i = $from->year, $il = $to->year; $i <= $il; $i++) {
    for ($j = 1, $jl = 12; $j <= $jl; $j++) {
      if ($i == $from->year && $j < $from->month) {
        continue;
      } else if ($i == $to->year && $j > $to->month) {
        continue;
      }
      $tmp = new stdClass();
      $tmp->month = $j;
      $tmp->year = $i;
      $result[] = $tmp;
    }
  }
  return $result;
}

function _days($year, $month) {
  if ($month == 1) {
    return 31;
  } else if ($month == 2) {
    if ($year % 4 == 0) {
      return 29;
    } else {
      return 28;
    }
  } else if ($month == 3) {
    return 31;
  } else if ($month == 4) {
    return 30;
  } else if ($month == 5) {
    return 31;
  } else if ($month == 6) {
    return 30;
  } else if ($month == 7) {
    return 31;
  } else if ($month == 8) {
    return 31;
  } else if ($month == 9) {
    return 30;
  } else if ($month == 10) {
    return 31;
  } else if ($month == 11) {
    return 30;
  } else if ($month == 12) {
    return 31;
  }
}


/**
 * 登录查询记录。。
 * ns.lanbinbin
 * 2011年8月4日 13:38:18
 */
function login() {
  $account = MiscUtils::getParam('a', NULL);
  $password = MiscUtils::getParam('p', START);
  
  $result = new stdClass();
  $result->data = array();
  
  $sql="select * from ns_v1user as d where d.account = '".$account."' AND d.password = '".$password."'";
  
  $result=getall($sql);
  
  if (count($result) == 1) {
    $user = $result[0];
    $_SESSION[OPERATOR] = $user;
    
    setcookie(OPERATOR, json_encode($user), (time() + 3600), PATH, DOMAIN);
    //print_r($_SESSION[OPERATOR]);
 
    //echo $_COOKIE[OPERATOR];
    echo json_encode($user);
  } else {
    echo json_encode(array());
  }
  
}


function customeradd($class,$debug=''){
    $obj= json_decode(MiscUtils::getParam('m', NULL));
    
     if(!empty($debug)){
      // print_r($obj);
     }
     
    $addsql = '';
    $fields = '';   
    foreach ($obj as $key => $value){
        
         if(!in_array($key ,array('sales','bride','groom','orders','userAccount'))){
            $fields.= $key.',';
            
            if( in_array($key,array('createdDate','cancelledDate') ) )
            {
            	if(is_object($obj->$key))
            	{
            		$value = SimpleDate::toStamp($value); //把日期转化为时间戳
            	}else{
            		if(empty($obj->$key)) $value = 0;
            	}
            }
            $addsql.=" '".addslashes($value)."',";
         }   
        

    }//end customer
     
    
    $fields .='userAccount';

    $addsql =substr($addsql,0,-1);

   $sql="insert into ns_".$class." (e_oid,".$fields.") values(NULL,".$addsql.",'".$obj->sales->name."')";
   
   if(!empty($debug)){
     echo $sql.'<br>';
   }else{
     sql_execute($sql);
     $customer_id = lastinsertid();
   }    
   unset($key);
   unset($value);
   
   
   
 /*
  *orders add 
  */  

    foreach($obj->orders as $order){//many orders
                 
             $addsqlorder = '';
             $fieldsorder = ''; 
                 
                foreach ($order as $key => $value){//one orders
                    
                    
                    if(!in_array($key ,array('disposaldate','disposaluserAccount','disposalstatus','disposalmessage','purchaseItems','payments',
                                             'customerId','photo','video','disposal'))){
                        $fieldsorder.= $key.',';
                        
                        if( in_array($key,array('createdDate','date','disposaldate') ) ) 
                        {
                        	if(is_object($order->$key))
                        	{
                        		$value = SimpleDate::toStamp($value); //把日期转化为时间戳
                        	}else{
                        		if(empty($order->$key)) $value = 0;
                        	}
                        }
                        $addsqlorder.=" '".addslashes($value)."',";
                    
                    }
                    

                }
                 
                    $fieldsorder .='customerId,disposalstatus';
                
                    $addsqlorder .="'".$customer_id."','0'"; 
                   
                    $ordersql="insert into ns_v1myorder (e_oid,".$fieldsorder.") values(NULL,".$addsqlorder.")";

                       if(!empty($debug)){
                         echo $ordersql.'<br>';
                       }else{   
                         sql_execute($ordersql);
                         $orderId = lastinsertid();     
                       }                    
                
            
               
                   unset($key);
                   unset($value);
                   

                      /*
                       * purchaseItems add   many PurchaseItem
                       * 
                       */
                       
                       foreach($order->purchaseItems  as $pitem){
                        
                           $addsqlpitem = '';
                           $fieldspitem = '';                             
                          foreach($pitem as $key => $value){
                            
                                if(!in_array($key ,array('selects','notes','_added','order_id','isFree'))){
                                $fieldspitem.= $key.',';
                                
                                $addsqlpitem.=" '".addslashes($value)."',";
                            
                            }                           
                          }//end one item
                          
                           $pitem->isFree = empty($pitem->isFree)? 0 : $pitem->isFree ;
                          
                        
                         $fieldspitem .='order_id,isFree';
                    
                         $addsqlpitem .="'".$orderId."','".$pitem->isFree."'"; 
                         
                         
                        
                         $pitemsql="insert into ns_v1purchaseitem (e_oid,".$fieldspitem.") values(NULL,".$addsqlpitem.")";                          

                           if(!empty($debug)){
                             echo $pitemsql.'<br>';
                           }else{   
                             sql_execute($pitemsql);
                           }                         
                         
                         $purchaseitem_id = lastinsertid();
                         
                         unset($key);
                         unset($value);                           
                         
                         /*
                          * purchaseitemselect add     many PurchaseItemSelect
                          * 
                          */
                         foreach($pitem->selects as $pis){
                            
                                   $addsqlpis = '';
                                   $fieldspis = '';                           
                                  foreach($pis as $key => $value){

                                    if(!in_array($key ,array('purchaseitem_id','packageitem_id'))){
                                        $fieldspis.= $key.',';
                                        
                                        $addsqlpis.=" '".addslashes($value)."',";
                                    }
                                    
                                    }    
                                                            
                                 $fieldspis .='purchaseitem_id';
                            
                                 $addsqlpis .="'".$purchaseitem_id."'"; 
                                
                                 
                                 $pissql="insert into ns_v1purchaseitemselect (e_oid,".$fieldspis.") values(NULL,".$addsqlpis.")";                          
                                  
                                   if(!empty($debug)){
                                     echo $pissql.'<br>';
                                   }else{   
                                     sql_execute($pissql);
                                   }                                 
                                 unset($key);
                                 unset($value);                                         
                                    
                            
                            
                         }//end purchaseItemSelect
                         
                         /*
                          * purchaseitemnotes add     many PurchaseNote
                          * 
                          */
                         foreach($pitem->notes as $notes){
                            
                                   $addsqlnote = '';
                                   $fieldsnote = '';                              
                                  foreach($notes as $key => $value){
                                     if(!in_array($key ,array('purchaseitem_id'))){
                                    
                                        $fieldsnote.= $key.',';
                                        
                                        if( in_array($key,array('date') ) )
                                        {
                                        	if(is_object($notes->$key))
                                        	{
                                        		$value = SimpleDate::toStamp($value); //把日期转化为时间戳
                                        	}else{
                                        		if(empty($notes->$key)) $value = 0 ;
                                        	}
                                        }
                                        $addsqlnote.=" '".addslashes($value)."',";
                                     }
                                    
                                    }                           
                                    
                                
                                 $fieldsnote .='purchaseitem_id';
                            
                                 $addsqlnote .="'".$purchaseitem_id."'"; 
                                
                                 $notesql="insert into ns_v1purchasenote (e_oid,".$fieldsnote.") values(NULL,".$addsqlnote.")";                         
                                
                                   if(!empty($debug)){
                                     echo $notesql.'<br>';
                                   }else{   
                                      sql_execute($notesql);
                                   }                                 
                                 unset($key);
                                 unset($value);                         
                            
                            
                         }//end notes                        
                         
                         
                       }//end purchaseitems
                       
                       
                       
                       /**
                        * 
                        *payments add  many Payment 
                        */
                       
                       
                       
                       
                       foreach($order->payments  as $payment){

                                   $addsqlpayment = '';
                                   $fieldspayment = '';                           
                                  foreach($payment as $key => $value){
                                    
                                        $fieldspayment.= $key.',';
                                        
                                        $addsqlpayment.=" '".addslashes($value)."',";
                                    
                                    }                           
                                    
                                
                                 $fieldspayment .='cutomerId,orderId';
                            
                                 $addsqlpayment .="'".$customer_id."','".$orderId."'"; 
                                
                                 $paymentsql="insert into ns_v1payment (e_oid,".$fieldspayment.") values(NULL,".$addsqlpayment.")";                         
                                  
                                 
                                   if(!empty($debug)){
                                     echo $paymentsql.'<br>';
                                   }else{   
                                      sql_execute($paymentsql);
                                   }                                 
                                 unset($key);
                                 unset($value);                                 
                        
                        
                       }//end payments      
                       
                       
    }//end orders
   
    customerfind('v1customer','',$customer_id);
}



/*
 * 
 * customer update
 * $action     tablename
 * $debug=''   not null:output sql;
 */
function customerupdate($action,$debug=''){
    $obj= json_decode(MiscUtils::getParam('m', NULL));
	if (isset($_COOKIE[OPERATOR])) { 
	 $coperator = json_decode($_COOKIE[OPERATOR]);
	}
	 
	$nowdate = date('Y-m-d H:i:s');
	$nowstamp = strtotime($nowdate);   
    
    if(!empty($debug)){
       print_r($obj);
    }
    
    
    if(!empty($obj)){
    
            $customersql = "update ns_".$action." set " ;
            foreach($obj as $key => $value)
            {
               if(!in_array($key,array('id','e_oid','orders','createdDate','cancelledDate','onote','sign','email') ))
               {
                  $customersql.= $key."='".addslashes($value)."',";
               }
            }//get all fields
            
            $customersql = substr($customersql,0,-1);
            $customersql.= " where e_oid = ".$obj->id." ";

            if(!empty($debug)){
                 echo "customer update Execute SQL:\n".$customersql."\n";
            }else{
                 sql_execute($customersql);
                 $customer_id = $obj->id;
            }       

             unset($key);
             unset($value);
             
           /**
            *order add(update)
            */
            if(!empty($obj->orders)){
            
                $original_order_id = getsonid('ns_v1myorder','e_oid','customerId',$obj->id);//原来的order_id数组
                 
                if(!empty($debug))
                {
                	echo "\n";
                	echo "*********原来的order_id*************";
                	echo "\n";
                    print_r($original_order_id);
                    echo "\n"; 
                }       
             
               $new_order_id = array();
               
               foreach($obj->orders as $order1)
               {
               	    if(isset($order1->e_oid) || isset($order1->id))
               	    {
               	    	$new_order_id[] = $order1->e_oid;
               	    }
               }

               $delete_order_id = array_diff($original_order_id, $new_order_id);//需要delete 的order_id
               
                if(!empty($debug))
                {
                    echo "\n";
                    echo "*********需要删除的order_id*************";
                    echo "\n";
                    print_r($delete_order_id);
                    echo "\n"; 
                } 
               
               if(!empty($delete_order_id))
               {
                    foreach($delete_order_id as $deleteid)
                    {
                         $pitem_id = getsonid('ns_v1purchaseitem','e_oid','order_id',$deleteid); 
                         
                              if(!empty($pitem_id))
                               {                          
                                     foreach($pitem_id as $pid)
                                     {
                                     	$paitem_id = operatebak('ns_h1purchaseitem','ns_v1purchaseitem','e_oid='.$pid,$coperator->account,$nowstamp,'delete'); 
                                     	
                                        $pselect_id = getsonid('ns_v1purchaseitemselect','e_oid','purchaseitem_id',$deleteid,'','1'); 
                                        
                                         if(!empty($pselect_id))
                                         {
                                         	 operatebak('ns_h1purchaseitemselect','ns_v1purchaseitemselect',"e_oid in ($pselect_id)",$paitem_id,$nowstamp,'delete');
                                             $pselectdelsql = "delete from ns_v1purchaseitemselect where e_oid in (".$pselect_id.")"; 
                                             if(!empty($debug))
                                             {
                                             	echo $pselectdelsql."\n";
                                             }else{
                                             	sql_execute($pselectdelsql); 
                                             }
                                         }
                                         
                                         $pnote_id = getsonid('ns_v1purchasenote','e_oid','purchaseitem_id',$deleteid,'','1');
                                         if(!empty($pnote_id))
                                         {
                                             $pnotedelsql = "delete from ns_v1purchasenote where e_oid in (".$pnote_id.")"; 
                                             if(!empty($debug))
                                             {
                                             	echo $pnotedelsql."\n";
                                             }else{
                                             	sql_execute($pnotedelsql);
                                             }
                                              
                                         }
                                         
                                         
                                         $pitemdelsql = "delete from ns_v1purchaseitem where e_oid = '".$pid."' ";
                                         if(!empty($debug))
                                         {
                                         	echo $pitemdelsql."\n";
                                         }else{
                                         	sql_execute($pitemdelsql); 
                                         }
                                     }
                         }//

                        operatebak('ns_h1myorder','ns_v1myorder','e_oid='.$deleteid,$coperator->account,$nowstamp,'delete');
                         
                        $orderdelsql = "delete from ns_v1myorder where e_oid = '".$deleteid."' ";
                        if(!empty($debug))
                        {
                        	echo $orderdelsql."\n";
                        }else{
                        	sql_execute($orderdelsql);                      
                        }
                    
                    }
                }//delete orders end            
               
               foreach($obj->orders as $order){//many orders
                                $order->pgprice = empty($order->pgprice) ? '0':$order->pgprice;
                                $order->vgprice = empty($order->vgprice) ? '0':$order->vgprice;
               	
                  if(isset($order->e_oid) || isset($order->id) ){//update orders
                  	            
                                operatebak('ns_h1myorder','ns_v1myorder','e_oid='.$order->e_oid,$coperator->account,$nowstamp,'modify'); 

                                
                                $ordersql = 'update ns_v1myorder  set ';
                                
                                foreach($order as $key => $value){//one order
                                
                                   if(!in_array($key,array('id','e_oid','createdDate','purchaseItems','payments','disposaldate','disposaluserAccount','disposalstatus','disposalmessage','sign') )){
                                     
                                    if(in_array($key,array('date')))
                                    {
                                    	if(is_object($order->$key))
                                    	{
                                    		if(is_object($order->$key))
                                    		{
                                    			$value = SimpleDate::toStamp($value);
                                    		}
                                    	}else{
                                    		if(empty($order->$key)) $value = 0;
                                    		
                                    	}
                                    }
                                    
                                    $ordersql.= $key."='".addslashes($value)."',";
                                    
                                   }
                                
                                }//end one order
                                
                                $ordersql = substr($ordersql,0,-1);
                                $ordersql.= " where e_oid = ".$order->e_oid." ";
                                
                                if(!empty($debug)){
                                    echo "order update Execute SQL:\n".$ordersql."\n";
                                }else{
                                    sql_execute($ordersql);
                                    $orderId = $order->e_oid;
                                }
                                
                                unset($key);
                                unset($value);
                   
                 }else{//add order
                 
                             $addsqlorder = '';
                             $fieldsorder = ''; 
                                 
                                foreach ($order as $key => $value)
                                {//one orders
                                    if(!in_array($key ,array('disposaldate','disposaluserAccount','disposalstatus','disposalmessage','purchaseItems','payments',
                                                             'customerId','photo','video','disposal'))){
                                        $fieldsorder.= $key.',';
                                        if( in_array($key,array('createdDate','date','disposaldate') ) )
                                        {
                                        	if(is_object($order->$key))
                                        	{
                                        		$value = SimpleDate::toStamp($value); //把日期转化为时间戳
                                        	}else{
                                        		if(empty($order->$key)) $value = 0; 
                                        	}
                                        }
                                        $addsqlorder.=" '".addslashes($value)."',";
                                    
                                    }
                                    

                                }
                                    $fieldsorder .='customerId,disposalstatus';
                                    $addsqlorder .="'".$customer_id."','0'"; 
                                    $ordersql="insert into ns_v1myorder (e_oid,".$fieldsorder.") values(NULl,".$addsqlorder.")";

                                       if(!empty($debug)){
                                         echo "order add Execute SQL:\n".$ordersql."\n";
                                       }else{   
                                         sql_execute($ordersql);
                                         $orderId = lastinsertid();
                                         operatebak('ns_h1myorder','ns_v1myorder','e_oid='.$orderId,$coperator->account,$nowstamp,'add');      
                                       }                    
                               
                                   unset($key);
                                   unset($value);                
                 
                 }//end order add
                 
                 
                 /**
                  * purchaseItems delete
                  * 
                  */
            if(!empty($order->purchaseItems)){
            
                $original_purchaseitem_id = getsonid('ns_v1purchaseitem','e_oid','order_id',$orderId);//原来的purchaseItem_id数组
                 
                if(!empty($debug))
                {
                    echo "\n";
                    echo "*********原来的purchaseitem_id*************";
                    echo "\n";
                    print_r($original_purchaseitem_id);
                    echo "\n"; 
                }       
             
               $new_purchaseitem_id = array();
               
               foreach($order->purchaseItems as $pitem1)
               {
               	    if(isset($pitem1->e_oid) || isset($pitem1->id))
               	    {
               	    	$new_purchaseitem_id[] = $pitem1->e_oid;
               	    }
               }

               $delete_purchaseitem_id = array_diff($original_purchaseitem_id, $new_purchaseitem_id);//需要delete 的delete_purchaseitem_id
               
                if(!empty($debug))
                {
                    echo "\n";
                    echo "*********需要删除的delete_purchaseitem_id*************";
                    echo "\n";
                    print_r($delete_purchaseitem_id);
                    echo "\n"; 
                } 
               
               if(!empty($delete_purchaseitem_id))
               {
                    foreach($delete_purchaseitem_id as $delete_puritemid)
                    {
                         //$pitem_id = getsonid('ns_v1purchaseitem','e_oid','order_id',$deleteid); 
                         
                              //if(!empty($pitem_id))
                               //{                          
                                    // foreach($pitem_id as $pid)
                                     //{
                                       $padelete_id = operatebak('ns_h1purchaseitem','ns_v1purchaseitem','e_oid ='.$delete_puritemid,$coperator->account,$nowstamp,'delete');
                                        $pselect_id = getsonid('ns_v1purchaseitemselect','e_oid','purchaseitem_id',$delete_puritemid,'','1'); 
                                        
                                         if(!empty($pselect_id))
                                         {
                                         	 operatebak('ns_h1purchaseitemselect','ns_v1purchaseitemselect',"e_oid in ($pselect_id)",$padelete_id,$nowstamp,'delete');
                                             $pselectdelsql = "delete from ns_v1purchaseitemselect where e_oid in (".$pselect_id.")"; 
                                             
                                             if(!empty($debug))
                                             {
                                             	echo $pselectdelsql."\n";
                                             }else{
                                             	sql_execute($pselectdelsql);
                                             }
                                              
                                         }
                                         
                                         $pnote_id = getsonid('ns_v1purchasenote','e_oid','purchaseitem_id',$delete_puritemid,'','1');
                                         if(!empty($pnote_id))
                                         {
                                             $pnotedelsql = "delete from ns_v1purchasenote where e_oid in (".$pnote_id.")"; 
                                             
                                             if(!empty($debug))
                                             {
                                             	echo $pnotedelsql."\n";
                                             }else{
                                             	sql_execute($pnotedelsql); 
                                             }
                                         }
                                         
                                        
                                         $pitemdelsql = "delete from ns_v1purchaseitem where e_oid = '".$delete_puritemid."' ";
                                         
                                         if(!empty($debug))
                                         {
                                         	echo $pitemdelsql."\n";
                                         }else{
                                         	sql_execute($pitemdelsql); 
                                         }
                    
                                         
                                     //}
                        // }//
                         
                    }
                }
              }//delete purchaseitems end                   
                 
                 
               /**
                *purchaseItems update or add
                */
                 if(!empty($order->purchaseItems))
                 {
                    foreach($order->purchaseItems as $pitem)
                    {//many items
                        
                    	if(isset($pitem->e_oid))
                    	{
                    	//purchaseitemselect delete start 2011年10月15日 16:38:34
			                $original_puis_id = getsonid('ns_v1purchaseitemselect','e_oid','purchaseitem_id',$pitem->e_oid);//原来的purchaseitemselect_id数组
			                 
			                if(!empty($debug))
			                {
			                    echo "\n";
			                    echo "*********原来的puriselect_id*************";
			                    echo "\n";
			                    print_r($original_puis_id);
			                    echo "\n"; 
			                }       
			             
			               $new_puiselect_id = array();
			               
			               foreach($pitem->selects as $puis1)
			               {
			                    if(isset($puis1->e_oid) || isset($puis1->id))
			                    {
			                        $new_puiselect_id[] = $puis1->e_oid;
			                    }
			               }
			
			               $delete_puis_id = array_diff($original_puis_id, $new_puiselect_id);//需要delete 的delete_purchaseitemselect_id  

			               if(!empty($delete_puis_id))
                           {
			                    foreach($delete_puis_id as $delete_puid)
			                    {
			                    	         operatebak('ns_h1purchaseitemselect','ns_v1purchaseitemselect',"e_oid in ($delete_puid)",0,$nowstamp,'delete'); 
			                                 $deloneselectsql = "delete from ns_v1purchaseitemselect where e_oid ='".$delete_puid."'"; 
                                             
                                             if(!empty($debug))
                                             {
                                                echo $deloneselectsql."\n";
                                             }else{
                                                sql_execute($deloneselectsql);
                                             }			                    	
			                    }
                           }			               
                    	
                    	//purchaseitemselect delete end
                    	}
                    	
                      if(isset($pitem->e_oid) || isset($pitem->id) )
                        {//update items
                        	   $caction = $pitem->cancelled == 1 ? 'delete':'modify';
                        	   $puitem_id = operatebak('ns_h1purchaseitem','ns_v1purchaseitem','e_oid ='.$pitem->e_oid,$coperator->account,$nowstamp,$caction); 
                        	   
                               $purchaseitemsql = "update ns_v1purchaseitem  set ";
                                foreach($pitem as $key => $value)
                                {
                                   if(!in_array($key,array('id','e_oid','selects','notes','_added','isFree')))
                                   {
                                     $purchaseitemsql.= $key."='".addslashes($value)."',";
                                   }
                                   
                                    if(in_array($key,array('isFree')))
                                    {
                                        if( empty($pitem->$key) ) $value = 0;
                                        $purchaseitemsql.= $key."='".addslashes($value)."',";                                   
                                        
                                    }                                   
                                }
                                
                                $purchaseitemsql = substr($purchaseitemsql,0,-1);
                                $purchaseitemsql.= " where e_oid = ".$pitem->e_oid." ";
                                
                                if(!empty($debug))
                                {
                                    echo "purchaseitem update Execute SQL:\n".$purchaseitemsql."\n";
                                }else{
                                    sql_execute($purchaseitemsql);
                                    $purchaseitem_id = $pitem->e_oid;
                                }
                                unset($key);
                                unset($value);  
                                
                        }else{//add items
                        
                                $addsqlpitem = '';
                                $fieldspitem = '';                            
                                  foreach($pitem as $key => $value)
                                  {
                                    if(!in_array($key ,array('selects','notes','_added','order_id','isFree','produce_trackId','v2_selects')))//2012年11月23日 10:26:22
                                    {
                                        $fieldspitem.= $key.',';
                                        $addsqlpitem.=" '".addslashes($value)."',";
                                    } 

                                    if(in_array($key,array('isFree')))
                                    {
                                    	if( empty($pitem->$key) ) $value = 0;
                                    	
                                        $fieldspitem.= $key.',';
                                        $addsqlpitem.=" '".addslashes($value)."',";                                    	
                                    	
                                    }
                                  }//end one item
                                  
                                
                                 $fieldspitem .='order_id';
                                 $addsqlpitem .="'".$orderId."'"; 
                                 $pitemsql="insert into ns_v1purchaseitem (e_oid,".$fieldspitem.") values(NULl,".$addsqlpitem.")";                          

                                   if(!empty($debug)){
                                     echo $pitemsql.'<br>';
                                   }else{   
                                     sql_execute($pitemsql);
                                     $purchaseitem_id = lastinsertid();
                                     $puitem_id = operatebak('ns_h1purchaseitem','ns_v1purchaseitem','e_oid ='.$purchaseitem_id,$coperator->account,$nowstamp,'add'); 
                                   }                         
                                 
                                 unset($key);
                                 unset($value);                             
                            
                        }//end itemsadd
                        
                        
                        
                            /**
                             *selects
                             *
                             */
                             
                             if(!empty($pitem->selects))
                             {
                                foreach($pitem->selects as $pselect)
                                {
                                    if(isset($pselect->id) || isset($pselect->e_oid))
                                    {//update select
                                    	   operatebak('ns_h1purchaseitemselect','ns_v1purchaseitemselect','e_oid ='.$pselect->e_oid,$puitem_id,$nowstamp,'modify');
                                    	   
                                           $pselectsql = 'update ns_v1purchaseitemselect  set ';
                                            foreach($pselect as $key => $value)
                                            {
                                               if(!in_array($key,array('id','e_oid')))
                                               {
                                                 $pselectsql.= $key."='".addslashes($value)."',";
                                               }
                                            }
                                            
                                            $pselectsql = substr($pselectsql,0,-1);
                                            $pselectsql.= " where e_oid = ".$pselect->e_oid." ";
                                            
                                            if(!empty($debug))
                                            {
                                                echo "purchaseitemselect update Execute SQL:\n".$pselectsql."\n";
                                            }else{
                                                sql_execute($pselectsql);
                                                //$purchaseitem_id = lastinsertid();
                                            }
                                            unset($key);
                                            unset($value);                                         
                                       
                                    }else{//add select
                                            $addsqlpis = '';
                                            $fieldspis = '';                              
                                            foreach($pselect as $key => $value)
                                                {
                                                    if(!in_array($key ,array('purchaseitem_id','packageitem_id','produce_trackId','purchase_trackId')))//2012年11月23日 10:26:01
                                                    {
                                                        $fieldspis.= $key.',';
                                                        $addsqlpis.=" '".addslashes($value)."',";
                                                    }
                                                }    
                                                                                
                                             $fieldspis .='purchaseitem_id';
                                             $addsqlpis .="'".$purchaseitem_id."'"; 
                                                     
                                             $pissql="insert into ns_v1purchaseitemselect (e_oid,".$fieldspis.") values(NULl,".$addsqlpis.")";                          
                                                      
                                                if(!empty($debug))
                                                {
                                                    echo "purchaseitemselect update Execute SQL:\n".$pissql."\n";
                                                }else{   
                                                    sql_execute($pissql);
                                                    $pis_id = lastinsertid();
                                                    operatebak('ns_h1purchaseitemselect','ns_v1purchaseitemselect','e_oid ='.$pis_id,$puitem_id,$nowstamp,'add');
                                                }
                                                
                                                unset($key);
                                                unset($value);                                          
                                    
                                    
                                    }//end select                                   
                                }
                             }//selects not null
                             
                             
                            /**
                             *notes
                             *
                             */ 

                             if(!empty($pitem->notes))
                             {
                                foreach($pitem->notes as $pnote)
                                {
                                    if(isset($pnote->id) || isset($pnote->e_oid))
                                    {//update note
                                           $pnotesql = 'update ns_v1purchasenote  set ';
                                            foreach($pnote as $key => $value)
                                            {
                                               if(!in_array($key,array('id','e_oid')))
                                               {
                                               	 if(in_array($key,array('date')))
                                               	 {
                                               	 	if(is_object($pnote->$key))
                                               	 	{
                                               	 		$value = SimpleDate::toStamp($value);
                                               	 	}else {
                                               	 		if(empty($pnote->$key) ) $value = 0;
                                               	 	}
                                               	 }
                                                 $pnotesql.= $key."='".addslashes($value)."',";
                                               }
                                            }
                                            
                                            $pnotesql = substr($pnotesql,0,-1);
                                            $pnotesql.= " where e_oid = ".$pnote->e_oid." ";
                                            
                                            if(!empty($debug))
                                            {
                                                echo "purchasenote update Execute SQL:\n".$pnotesql."\n";
                                            }else{
                                                sql_execute($pnotesql);
                                                //$purchaseitem_id = lastinsertid();
                                            }
                                            unset($key);
                                            unset($value);                                         
                                       
                                    }else{//add note
                                            $addsqlnote = '';
                                            $fieldsnote = '';                             
                                            foreach($pnote as $key => $value)
                                                {
                                                    if(!in_array($key ,array('purchaseitem_id')))
                                                    {
                                                        $fieldsnote.= $key.',';
                                                        
                                                        if(in_array($key,array('date')))
                                                        {
                                                        	if(is_object($pnote->$key))
                                                        	{
                                                        		$value = SimpleDate::toStamp($value);
                                                        	}else {
                                                        		if(empty($pnote->$key)) $value = 0;
                                                        	}
                                                        }
                                                        $addsqlnote.=" '".addslashes($value)."',";
                                                    }
                                                }    
                                                                                
                                             $fieldsnote .='purchaseitem_id';
                                             $addsqlnote .="'".$purchaseitem_id."'"; 
                                                     
                                             $pissql="insert into ns_v1purchasenote (e_oid,".$fieldsnote.") values(NULl,".$addsqlnote.")";                          
                                                      
                                                if(!empty($debug))
                                                {
                                                    echo "purchasenote update Execute SQL:\n".$pissql."\n";
                                                }else{   
                                                    sql_execute($pissql);
                                                }
                                                
                                                unset($key);
                                                unset($value);                                          
                                    
                                    
                                    }//end note                                     
                                }
                             }//notes not null                           
                        
                    }//end foreach items
                     
                        
                     
                     }//itmes not null 

               }//end foreach orders
            
            
            }
    }

    customerfind('v1customer','',$obj->id);
    
}


 /*
  * customer 
  * 
  */
 function customerfind($action,$condition,$e_oid,$flag=''){
    
  $condition = MiscUtils::getParam('c', 'where 1 = 1'); 
  $condition .= ($e_oid) ? ' AND c.e_oid = \'' . $e_oid . '\'' : '';
  
  $result = new stdClass();
  $result->data = array(); 

  
  
  
  
    $sql2 = "SELECT c.e_oid as id, c.* FROM ns_".$action." as c $condition";
    
    
    $tmp=getall($sql2);
    
    
        foreach($tmp as $tmp2){
            
            //get orders
            $tmp2->orders =array();
            
            $tmporder = getsonall('ns_v1myorder','customerId',$tmp2->id);
            
            
            $tmp2->orders = $tmporder; 
            
            foreach($tmporder as $order){
              //get purchaseitem
              $order->purchaseItems = array();
              $pitem = getsonall('ns_v1purchaseitem','order_id',$order->e_oid);
              
               foreach($pitem as $pis){
                 $pis->selects = array();//selects
                 $pis->notes =array();//notes
                 
                 $selectarr = getsonall('ns_v1purchaseitemselect','purchaseitem_id',$pis->e_oid);
                 $notearr = getsonall('ns_v1purchasenote','purchaseitem_id',$pis->e_oid);
                 
                 foreach($selectarr as $select){
                    $pis->selects[] = $select;  
                    
                 }
                 
                 foreach($notearr as $notes){
                   $pis->notes[] = $notes;  
                    
                 }
                 
                 
                 $order->purchaseItems[] = $pis;
                 
               }//end purchaseitem
               
              $order->payments = array();
              $payment = getsonall('ns_v1payment','orderId',$order->e_oid); 
              $order->payments = $payment;
              
              
              
                
              //$tmp211 = getsonall('ns_v1packageitemselect','parentId1',$v21->e_oid);
              //$v21->selects =  array();
              
              //$v21->selects =$tmp211;
            }//end orders
            
            //$tmp2->createdDate = SimpleDate::fromStamp($tmp2->createdDate);
            //$tmp2->cancelledDate = SimpleDate::fromStamp($tmp2->cancelledDate);
                    
            
            
            $result->data[] = $tmp2;
        }//end customer

  echo json_encode($result);        
    
 }
 
 /**
  * packagepurchaseupdate
  */
   function packagepurchaseupdate($action,$debug='')
   {
      $sample = json_decode(MiscUtils::getParam('sp', NULL));
      $purchases = json_decode(MiscUtils::getParam('ps', NULL));
      $packageitem = json_decode(MiscUtils::getParam('pi', NULL));
      
      if(!empty($debug))
      {
        echo "****************以下为sample *******************************";
        print_r($sample);
        echo"\n";
      }
      
      if(!empty($sample))
      {
            $samplesql = "update ns_v1sample set ";
            foreach($sample as $key => $value)
            {
                if(!in_array($key,array('attributes','id','e_oid')))
                {
                  $samplesql .= " `$key` = '".$value."',";
                }
            }
            
            $samplesql =substr($samplesql,0,-1);
            $samplesql.=" where e_oid='".$sample->e_oid."'";
    
            if(!empty($debug))
            {
                echo $samplesql."\n";
            }else{
                sql_execute($samplesql);    
            }
             
            unset($key);
            unset($value);
            
                /**
                 * delete start
                 */
                $original_sampleattribute_id = getsonid('ns_v1sampleattribute','e_oid','sample_id',$sample->e_oid);//原来的ns_v1sampleattribute数组
                 
                if(!empty($debug))
                {
                   print_r($original_sampleattribute_id); 
                }       
             
               $new_sampleattribute_id = array();
               
               foreach($sample->attributes as $sattribute1)
               {
                    $new_sampleattribute_id[] = $sattribute1->e_oid;
               }

               $delete_soption_id = array_diff($original_sampleattribute_id, $new_sampleattribute_id);//需要delete 的packageitem_id
               
               if(!empty($delete_soption_id))
               {
                    foreach($delete_soption_id as $deleteid)
                    {
                         $soption_id = getsonid('ns_v1sampleattributeoption','e_oid','sampleattribute_id',$deleteid); 
                         
                              if(!empty($soption_id))
                               {                          
                                     foreach($soption_id as $pid)
                                     {
                                         $soptionsql = "delete from ns_v1sampleattributeoption where e_oid = '".$pid."' ";
                                         sql_execute($soptionsql); 
                                     }
                               }//
                            
                        $sampleattributesql = "delete from ns_v1sampleattribute where e_oid = '".$deleteid."' ";
                        sql_execute($sampleattributesql);                       
                    
                    }
                }//delete packitems end                 

                /**
                 * delete end
                 */         
            
            if(!empty($sample->attributes) )
            {
            	
                foreach($sample->attributes as $spattibute)
                {
                    $spattibutesql =" update ns_v1sampleattribute set ";
                    
                    foreach($spattibute as $key => $value)
                    {
                        if(!in_array($key,array('options','id','e_oid')))
                        {
                            $spattibutesql .= " `$key` = '".$value."',";
                        }
                    }
                    
                    $spattibutesql =substr($spattibutesql,0,-1);
                    $spattibutesql.=" where e_oid='".$spattibute->e_oid."'";
            
                    if(!empty($debug))
                    {
                        echo $spattibutesql."\n";
                    }else{
                        sql_execute($spattibutesql);    
                    }
                     
                    unset($key);
                    unset($value);

                    /**
                     * options
                     */
                    if(!empty($spattibute->options))
                    {
                        /**
                         * delete options start
                         */
                            $original_options_id = getsonid('ns_v1sampleattributeoption','e_oid','sampleattribute_id',$spattibute->e_oid);//原来的ns_v1sampleattributeoptins数组
                             
                            if(!empty($debug))
                            {
                               print_r($original_options_id); 
                            }       
                         
                           $new_options_id = array();
                           
                           foreach($spattibute->options as $soptions1)
                           {
                                $new_options_id[] = $soptions1->e_oid;
                           }
            
                           $delete_options_id = array_diff($original_options_id, $new_options_id);//需要delete 的sampleattribute_id
                           
                           if(!empty($delete_options_id))
                           {
                                foreach($delete_options_id as $deloptionid)
                                {
                                        
                                    $deloptionsql = "delete from ns_v1sampleattributeoption where e_oid = '".$deloptionid."'";
                                    sql_execute($deloptionsql);                       
                                
                                }
                            }//delete sampleattribute end                       
                        
                        /**
                         * delete options end
                         */                    	
                    	
                        foreach($spattibute->options as $spoption)
                        {
                            $spoptionsql = " update ns_v1sampleattributeoption set ";
                            foreach($spoption as $key => $value)
                            {
                               if(!in_array($key,array('id','e_oid')))
                                {
                                    $spoptionsql .= " `$key` = '".$value."',";
                                }                               
                                
                            }
                            
                                $spoptionsql =substr($spoptionsql,0,-1);
                                $spoptionsql.=" where e_oid='".$spoption->e_oid."'";
                        
                                if(!empty($debug))
                                {
                                    echo $spoptionsql."\n";
                                }else{
                                    sql_execute($spoptionsql);  
                                }
                                unset($key);
                                unset($value);  
                                                        
                        }
                    }
                    
                }
                

                
                
            }      
        
      }//not null sample
      
      if(!empty($debug))
      {
        echo "****************以下为purchases *******************************";
        print_r($purchases);
        echo"\n";               
      }      
      
      if(!empty($purchases))
      {
      	foreach ($purchases as $purchaseitem)
      	{
		        $purchasesql = "update ns_v1purchaseitem set ";
		        foreach($purchaseitem as $key => $value)
		        {
		            if(!in_array($key,array('selects','id','e_oid','notes')))
		            {
		               $purchasesql .= " `$key` = '".$value."',";
		            }
		        }
		        
		        $purchasesql =substr($purchasesql,0,-1);
		        $purchasesql.=" where e_oid='".$purchaseitem->e_oid."'";
		                
		        if(!empty($debug))
		        {
		            echo $purchasesql."\n";
		        }else{
		            sql_execute($purchasesql);  
		        }
		        unset($key);
		        unset($value);
		
		        /**
		         * selects
		         */
		         if(!empty($purchaseitem ->selects))
		         {
		            foreach($purchaseitem ->selects as $select)
		            {
		                $purchaseselectsql = "update ns_v1purchaseitemselect set ";
		                foreach($select as $key => $value)
		                {
		                    if(!in_array($key,array('id','e_oid')))
		                    {
		                        $purchaseselectsql .= " `$key` = '".$value."',";
		                    }
		                    
		                }
		                
		                $purchaseselectsql =substr($purchaseselectsql,0,-1);
		                $purchaseselectsql.=" where e_oid='".$select->e_oid."'";
		                        
		                if(!empty($debug))
		                {
		                    echo $purchaseselectsql."\n";
		                }else{
		                    sql_execute($purchaseselectsql);    
		                }
		                unset($key);
		                unset($value);
		                
		            }
		            
		            
		         }
      	}//one  purchaseitem  end
        
      }//not null $purchases
      
      
      /**
       * packageitem
       * 
       */
      if(!empty($debug))
      {
        echo "****************以下为packageitems *******************************";
        print_r($packageitem);
        echo"\n";               
      }

      if(!empty($packageitem))
      {
      	foreach ($packageitem as $packitem)
      	{
		      	$packageitemsql = "update ns_v1packageitem set ";
		      	foreach ($packitem as $key => $value)
		      	{
		      		if(!in_array($key,array('selects','id','e_oid')))
		      		{
		      			$packageitemsql .= " `$key` = '".$value."',";
		      		}
		      		
		      	}
		      	
		        $packageitemsql =substr($packageitemsql,0,-1);
		        $packageitemsql.=" where e_oid='".$packitem->e_oid."'";
		                       
		        if(!empty($debug))
		        {
		           echo $packageitemsql."\n";
		        }else{
		           sql_execute($packageitemsql);    
		        }
		        unset($key);
		        unset($value);
		        
                /**
                 * delete start
                 * 2011年9月13日 12:47:03
                 */
                $original_packageitemselect_id = getsonid('ns_v1packageitemselect','e_oid','packageitem_id',$packitem->e_oid);//原来的ns_v1packageitemselect数组
                 
                if(!empty($debug))
                {
                   print_r($original_packageitemselect_id); 
                }       
             
               $new_packageitemselect_id = array();
               
               if(!empty($packitem->selects))
               {
	               foreach($packitem->selects as $piselect1)
	               {
	                    $new_packageitemselect_id[] = $piselect1->e_oid;
	               }
               }

               $delete_piselect_id = array_diff($original_packageitemselect_id, $new_packageitemselect_id);//需要delete 的packageitemselect_id
               
               if(!empty($delete_piselect_id))
               {
                    foreach($delete_piselect_id as $deleteselectid)
                    {
                        $packageitemselectsql = "delete from ns_v1packageitemselect where e_oid = '".$deleteselectid."' ";
                        if(!empty($debug))
                        {
                        	echo $packageitemselectsql."\n";
                        }else{
                        	sql_execute($packageitemselectsql);                       
                        }
                    
                    }
                }//delete packitems end                 

                /**
                 * delete end
                 */ 		        
		        
		
		        /**
		         * selects
		         */
		        
		        if(!empty($packitem->selects))
		        {
		        	foreach ($packitem->selects as $piselect)
		        	{
		        		$packageitemselectsql = "update ns_v1packageitemselect set ";
		        		foreach ($piselect as $key => $value)
		        		{
		        			if(!in_array($key,array('id','e_oid')))
		        			{
		        				$packageitemselectsql .= " `$key` = '".$value."',";
		        			}
		        			
		        		}
		        		
				        $packageitemselectsql =substr($packageitemselectsql,0,-1);
				        $packageitemselectsql.=" where e_oid='".$piselect->e_oid."'";
				                       
				        if(!empty($debug))
				        {
				           echo $packageitemselectsql."\n";
				        }else{
				           sql_execute($packageitemselectsql);    
				        }
				        unset($key);
		        unset($value);       		
		        		
		        	}
		         
		        }
      	
      	}//one packageitem end
      	
      }//packageitem not null
    
    
       
   }
 








?>